﻿using System.IO;
using System.Windows.Documents;
using System.Windows.Media.Imaging;
using System.Windows.Xps.Packaging;

namespace MediaBrowser.Gui.Tools
{
    public class XPSConversion
    {
        /// <summary>
        ///  Transforme un fichier XPS en une série d'images
        /// </summary>
        /// <param name="xpsFileName"></param>
        /// <param name="directory"></param>
        /// <returns></returns>
        public int SaveXpsPageToBitmap(string xpsFileName, string directory)
        {
            //Create Directory
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            // XPS Document
            XpsDocument xpsDoc = new XpsDocument(xpsFileName, System.IO.FileAccess.Read);
            FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence();

            // Nombre de pages
            int pageCount = docSeq.References[0].GetDocument(false).Pages.Count;

            // Convert a XPS page to a PNG file
            for (int pageNum = 0; pageNum < pageCount; pageNum++)
            {
                DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageNum);
                BitmapImage bitmap = new BitmapImage();
                RenderTargetBitmap renderTarget =
                    new RenderTargetBitmap((int)docPage.Size.Width,
                                            (int)docPage.Size.Height,
                                            96,
                                            96,
                                            System.Windows.Media.PixelFormats.Pbgra32);
                renderTarget.Render(docPage.Visual);

                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderTarget));

                FileStream pageOutStream = new FileStream(directory + pageNum + ".png", FileMode.Create, FileAccess.Write);
                encoder.Save(pageOutStream);
                pageOutStream.Close();
            }          
            xpsDoc.Close();

            return pageCount;
        }
    }
}
